import {
  ALL,
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Param,
  Post,
  Provide,
  Put,
  Validate,
} from '@midwayjs/decorator';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';
import { FlowNodeDto } from '../dto';
import { TbFlow } from '../entity/TbFlow';
import { TbFlowNode } from '../entity/TbFlowNode';
import { FlowService } from '../service/flow';

@Provide()
@Controller('/flows', { tagName: '流程管理' })
export class FlowController {
  @Inject()
  ctx: Context;

  @Inject()
  flowService: FlowService;

  @InjectEntityModel(TbFlow)
  flowModel: Repository<TbFlow>;

  @InjectEntityModel(TbFlow)
  flowNodeModel: Repository<TbFlowNode>;

  @Get('/', { summary: '获取流程列表' })
  async index() {
    return this.flowModel.find();
  }
  @Get('/:id', { summary: '获取流程详情' })
  async show(@Param() id: number) {
    return this.flowModel.findOne(id);
  }
  @Post('/init', { summary: '初始化流程' })
  async init() {
    await this.flowService.initFlowEHSY();
  }
  @Put('/:id/node/:nodeId', { summary: '修改流程节点' })
  @Validate()
  async update(
    @Param() id: number,
    @Param() nodeId: number,
    @Body(ALL) body: FlowNodeDto
  ) {
    const node = await this.flowNodeModel.findOne({
      where: {
        id: nodeId,
        flowId: id,
      },
    });
    if (!node) {
      this.ctx.throw(404, '节点不存在');
    }
    this.flowNodeModel.merge(node, body);
    await this.flowNodeModel.save(node);
    return node;
  }
  // @Del('/:id', { summary: '删除流程' })
  // async delete() {}
}
